package com.fxc.filter;

import com.fxc.crowd.constant.AccessPassResources;
import com.fxc.crowd.constant.CrowdConstant;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author FXC
 * @version 1.0
 * @date 2021/12/9 15:52
 */
@Component
public class CrowdAccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        // 这里返回“pre”意思实在目标微服务前执行过滤
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {

        // 1.获取RequestContext对象
        RequestContext currentContext = RequestContext.getCurrentContext();

        // 2.通过RequestContext对象获取当前请求对象（框架底层借助ThreadLocal从当前线程上获取事先绑定的Request）
        HttpServletRequest request = currentContext.getRequest();

        // 3.获取servlet的值
        String servletPath = request.getServletPath();

        // 4.根据servletPath判断当前请求是否对应可以直接放行的特定功能
        boolean contains = AccessPassResources.PASS_RES_SET.contains(servletPath);

        if (contains){

            // 如果当前请求是可以直接放行的特定功能请求则返回false放行
            return false;
        }

        // 判断当前请求是否为静态资源
        // 工具方法返回true：说明当前请求是静态资源请求，取反为false表示放行不做登录检查
        // 工具方法返回false：说明当前请求不是可以放行的特定请求也不是静态资源
        boolean judgeStaticResult = AccessPassResources.judgeCurrentServletPathWeatherStaticResource(servletPath);

        if (judgeStaticResult){
            return false;
        }

        return true;
    }

    @Override
    public Object run() throws ZuulException {

        // 1.获取当前请求对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        // 2.获取当前session对象中获取已登录的用户
        HttpSession session = request.getSession();

        // 3.尝试获取session对象中已登录的用户
        Object loginMember = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);

        // 4.判断loginMember是否为空
        if (loginMember == null){

            // 5从requestContext对象中获取Response对象
            HttpServletResponse response = requestContext.getResponse();

            // 6.将提示消息存入session域
            session.setAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_ACCESS_FORBIDDEN);

            // 7.重定向auth—consumer工程中的登录页面
            try {
                response.sendRedirect("http://localhost:8081/auth/member/to/login/page");
            }catch (IOException e){
                e.printStackTrace();
            }
        }

        return null;
    }
}
